package com.fingard.dsp.bank.directbank.cmbc01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ICashPool;
import com.fingard.dsp.bank.reqrespobj.cashpool.*;
import com.fingard.dsp.bank.reqrespobj.cashpool.Detail.RetAtsCPAQCashPoolAccQryDetail;
import com.fingard.dsp.bank.reqrespobj.cashpool.Detail.RetAtsCPTQCashPoolTreeQryDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.*;
@Component("CMBC01CashPool")
public class CMBC01CashPool extends CMBC01Base implements ICashPool {
    //inster(主键，渠道，账户ID，账户，是否民生标志，账号类型)
    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,OUTREQSEQID,REQSEQID,RESERVE1,RESERVE2) values (?,?,?,?,?,?);";
    private static final String UPDATERECEIPT = "UPDATE REQSEQIDMAPPING SET REQSEQID=?,RESERVE1=?,RESERVE2=? WHERE OUTREQSEQID=?;";


    /**
     * 民生银行全球组织机构关系树查询
     *
     * @param cptq
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsCPTQCashPoolTreeQry CPTQ_CashPoolTreeQry(ReqCPTQCashPoolTreeQry cptq) throws Exception {
        RetAtsCPTQCashPoolTreeQry retAts = new RetAtsCPTQCashPoolTreeQry(cptq.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            //赋值通用参数
            CMBC01Header bankHeader = new CMBC01Header();
            bankHeader.trnCode = "CBCashPoolTreeQry";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);

            xmlWriter.writeStartElement("xDataBody");
            xmlWriter.writeElementString("trnId", Format.DateTime17Format.format(new Date()));
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                    String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                    if (tmpRetCode.equals("0")) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmpRetMessage;
                        retAts.trnId = tmpBkReader.getFirstText("/CMBC/xDataBody/trnId");
                        retAts.totalNum = tmpBkReader.getFirstText("/CMBC/xDataBody/totalNum");
                        while (tmpBkReader.read("/CMBC/xDataBody/List/Map")) {
                            XElement readXElement = tmpBkReader.readedXElement;
                            RetAtsCPTQCashPoolTreeQryDetail tmpRetDetail = new RetAtsCPTQCashPoolTreeQryDetail();
                            tmpRetDetail.customId = readXElement.getSingleText("customId");//客户编号
                            tmpRetDetail.treeNodeId = readXElement.getSingleText("treeNodeId");//客户关系树节点 ID
                            tmpRetDetail.treeParentNodeId = readXElement.getSingleText("treeParentNodeId");//客户关系树父节点 ID
                            tmpRetDetail.level = readXElement.getSingleText("level");//客户在整棵树中的所处层级
                            tmpRetDetail.customNameCn = readXElement.getSingleText("customNameCn");//客户中文名称
                            tmpRetDetail.upCustomNameCn = readXElement.getSingleText("upCustomNameCn");//上级客户中文名称
                            tmpRetDetail.hasChild = readXElement.getSingleText("hasChild");//是否具有子节点 true-有子节点 false-无子节点
                            retAts.writeDetail(tmpRetDetail);
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetMessage;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = "全球现金池组织结构关系树查询异常";
            e.printStackTrace();
            WriteBankLogLn("全球现金池账号查询余额异常，异常信息：" + e.getMessage());
        }
        retAts.writeAfter();
        return retAts;
    }

    /**
     * 民生银行全球账户信息查询
     *
     * @param cpaq
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsCPAQCashPoolAccQry CPAQ_CashPoolAccQry(ReqCPAQCashPoolAccQry cpaq) throws Exception {
        /**
         * 将查询的账号ID、账号、是否民生标志、账号类型存入DSP数据库，查询余额的时候根据账号ID、账号 获取是否民生标志与账号类型
         */

        RetAtsCPAQCashPoolAccQry retAts = new RetAtsCPAQCashPoolAccQry(cpaq.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息//赋值通用参数
        Connection conn = FGBiz.getLocalDbConn();

        try {
            //每个客户编号都去查询一次账号信息
            while (cpaq.readRecord()) {
                String tmpRespCode = "";
                String tmpRespInfo = "";
                List<RetAtsCPAQCashPoolAccQryDetail> accQryDetailList = new ArrayList<RetAtsCPAQCashPoolAccQryDetail>();
                /**
                 * 每个客户编号查询分页查询账号信息，发送报文
                 */
                int tmpNowReadStart = 1;//起始页数
                int tmpNowReadNum = 0;//已查询笔数
                Map<String, Integer> tmpTotalNum = new HashMap<String, Integer>();
                while (tmpNowReadNum == 0 || tmpNowReadNum < tmpTotalNum.get("totalCount")) {
                    //赋值通用参数
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    CMBC01Header bankHeader = new CMBC01Header();
                    bankHeader.trnCode = "CBCashPoolAccInfoQry";
                    writeCommonHeader(xmlWriter, bankHeader);
                    xmlWriter.writeStartElement("xDataBody");
                    xmlWriter.writeElementString("trnId", Format.DateTime17Format.format(new Date()));
                    xmlWriter.writeElementString("customId", cpaq.readedDetail.customId);
                    //isQryNextLevel0 - 不查下级账户1 - 查询下级账户
                    xmlWriter.writeElementString("isQryNextLevel", StringHelper.isNullOrEmpty(cpaq.readedDetail.isQryNextLevel) ? "0" : cpaq.readedDetail.isQryNextLevel);
                    xmlWriter.writeElementString("pageNo", tmpNowReadStart + "");//当前页数
                    xmlWriter.writeElementString("pageSize", getBankConfig().getValueAsString("pageSize"));//每页查询笔数
                    xmlWriter.writeEndDocument();

                    String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());

                    if (tmpRetBkStr[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                            String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                            if (tmpRetCode.equals("0")) {
                                //符合条件的条数，总明细数
                                String totalCount = tmpBkReader.getFirstText("/CMBC/xDataBody/allNum");
                                if (tmpTotalNum.containsKey("totalCount")) {
                                    if (!tmpTotalNum.get("totalCount").equals(Integer.valueOf(totalCount))) {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "相同条件前后查出来的总数不一致";
                                        break;
                                    }
                                } else {
                                    if ("0".equals(totalCount)) {
                                        tmpRespCode = "0";
                                        tmpRespInfo = "该客户编号账户数为0";
                                        break;
                                    }
                                    tmpTotalNum.put("totalCount", Integer.valueOf(totalCount));//记录总条数
                                }

                                int readCount = 0;
                                while (tmpBkReader.read("/CMBC/xDataBody/List/Map")) {
                                    XElement readXElement = tmpBkReader.readedXElement;
                                    RetAtsCPAQCashPoolAccQryDetail tmpRetAccInfoDetail = new RetAtsCPAQCashPoolAccQryDetail();
                                    tmpRetAccInfoDetail.accountId = readXElement.getSingleText("accountId");//帐号 ID
                                    tmpRetAccInfoDetail.account = readXElement.getSingleText("account");//帐号
                                    tmpRetAccInfoDetail.accName = readXElement.getSingleText("accName");//账号名称
                                    tmpRetAccInfoDetail.accUserBal = readXElement.getSingleText("accUserBal");//可用余额
                                    tmpRetAccInfoDetail.accBal = readXElement.getSingleText("accBal");//账户余额
                                    tmpRetAccInfoDetail.isCmbc = readXElement.getSingleText("isCmbc");//是否是民生银行标志0-他行账户1-民生银行账户
                                    tmpRetAccInfoDetail.accountType = readXElement.getSingleText("accountType");//账号类型1-境内分行账户；2-境外分行账户；3-他行账户
                                    tmpRetAccInfoDetail.curCode = convertCurToATS(readXElement.getSingleText("currencyName"));//币种编码
                                    tmpRetAccInfoDetail.currencyName = readXElement.getSingleText("currencyName");//币种名称
                                    tmpRetAccInfoDetail.bankName = readXElement.getSingleText("bankName");//开户行名称
                                    tmpRetAccInfoDetail.countryName = readXElement.getSingleText("countryName");//开户行所在国家
                                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                    //inster(主键，渠道，账户ID，账户，是否民生标志，账号类型)
                                    if (JDBCHelper.update(conn, UPDATERECEIPT, new Object[]{tmpRetAccInfoDetail.account, tmpRetAccInfoDetail.isCmbc, tmpRetAccInfoDetail.accountType, tmpRetAccInfoDetail.accountId}) == 0) {
                                        JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, cpaq.reqHeader.bankCode, tmpRetAccInfoDetail.accountId, tmpRetAccInfoDetail.account, tmpRetAccInfoDetail.isCmbc, tmpRetAccInfoDetail.accountType});
                                    }
                                    accQryDetailList.add(tmpRetAccInfoDetail);
                                    readCount++;
                                }

                                tmpNowReadNum += readCount;//已查询条数
                                if (Integer.parseInt(totalCount) > tmpNowReadNum) {
                                    //总条数大于已查询条数，说明查询了默认条数的明细
                                    if (readCount != Integer.valueOf(getBankConfig().getValueAsString("pageSize"))) {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "总条数大于已查询条数,统计明细有误";
                                        break;
                                    }
                                }
                                if (Integer.parseInt(totalCount) < tmpNowReadNum) {
                                    //总条数小于已查询条数,说明数据异常
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "总条数小于已查询条数,统计明细有误";
                                    break;
                                }
                                tmpNowReadStart++;//查询起始页加1
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpRetMessage;
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpRetBkStr[1];
                        break;
                    }
                }//while(分页)
                if (!StringHelper.isNullOrEmpty(tmpRespCode)) {
                    retAts.customId = cpaq.readedDetail.customId;//客户编号
                    retAts.respCode = tmpRespCode;
                    retAts.respInfo = tmpRespInfo;
                    retAts.writeDetail();
                    retAts.writeDetailEnd();
                } else {
                    retAts.customId = cpaq.readedDetail.customId;//客户编号
                    retAts.respCode = "0";
                    retAts.respInfo = "该客户编号查询账号信息成功！";
                    retAts.writeDetail();
                    for (int i = 0; i < accQryDetailList.size(); i++) {
                        retAts.writeAccInfo(accQryDetailList.get(i));
                    }
                    retAts.writeDetailEnd();
                }
            }//while(cpaq.readRecord())
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = "查询民生银行全球现金池账户信息异常!";
            e.printStackTrace();
            WriteBankLogLn("查询民生银行全球现金池账户信息异常，异常信息：" + e.getMessage());
        } finally {
            conn.close();
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 全球现金池账户签约信息查询
     *
     * @param cpasq
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsCPASQCashPoolAccSignInfoQry CPASQ_CashPoolAccSignInfoQry(ReqCPASQCashPoolAccSignInfoQry cpasq) throws Exception {
        RetAtsCPASQCashPoolAccSignInfoQry retAts = new RetAtsCPASQCashPoolAccSignInfoQry(cpasq.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息//赋值通用参数
        try {
            //赋值通用参数
            CMBC01Header bankHeader = new CMBC01Header();
            bankHeader.trnCode = "CBAccSignInfoQry";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);

            xmlWriter.writeStartElement("xDataBody");
            xmlWriter.writeElementString("trnId", Format.DateTime17Format.format(new Date()));
            xmlWriter.writeElementString("accountId", cpasq.accountId);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBC/responseHeader/status/code");
                    String tmpRetMessage = tmpBkReader.getFirstText("/CMBC/responseHeader/status/message");
                    if (tmpRetCode.equals("0")) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmpRetMessage;
                        retAts.trnId = tmpBkReader.getFirstText("/CMBC/xDataBody/trnId");
                        retAts.custName = tmpBkReader.getFirstText("/CMBC/xDataBody/custName");
                        retAts.regName = tmpBkReader.getFirstText("/CMBC/xDataBody/regName");
                        retAts.account = tmpBkReader.getFirstText("/CMBC/xDataBody/account");
//                        retAts.currencyCode = convertCurToATS(tmpBkReader.getFirstText("/CMBC/xDataBody/currencyCode"));
                        retAts.currencyCode = tmpBkReader.getFirstText("/CMBC/xDataBody/currencyCode");
                        retAts.bankName = tmpBkReader.getFirstText("/CMBC/xDataBody/bankName");
                        retAts.countryName = tmpBkReader.getFirstText("/CMBC/xDataBody/countryName");
                        retAts.accTypeName = tmpBkReader.getFirstText("/CMBC/xDataBody/accTypeName");
                        retAts.accType = tmpBkReader.getFirstText("/CMBC/xDataBody/accType");
                        retAts.accContact = tmpBkReader.getFirstText("/CMBC/xDataBody/accContact");
                        retAts.contactphone = tmpBkReader.getFirstText("/CMBC/xDataBody/contactphone");
                        retAts.upAccount = tmpBkReader.getFirstText("/CMBC/xDataBody/upAccount");
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpRetMessage;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = "全球现金池账户签约信息查询异常";
            e.printStackTrace();
            WriteBankLogLn("全球现金池账户签约信息查询异常，异常信息：" + e.getMessage());
        }
        retAts.writeAfter();
        return retAts;
    }
}
